﻿$.fn.DataGrid = {
    DataBind: function (obj) {
        var _default = {
            id: "dg1"

            , url: null
            , data: {}
            , deleteUrl: {}
            , deleteData: {}

            //基本属性
            , title: null
            , key: "id"

            , editUrl: null//编辑地址
            , addUrl: obj.editUrl//添加
            , detailsUrl: obj.editUrl //详细双击

            //弹出窗口属性  
            , dialogName: "操作窗口"
            , dialogID: obj.id + "_01"
            , dialogWidth: ""
            , dialogHeight: ""

            //分页
            , pages: { pagination: true, pageNumber: 1, pageSize: 15, pageList: [2, 10, 15, 20, 25, 30, 40, 50], total: 0 }
            , orderBy: { sort: "id", order: "desc" }

            //工具栏
            , toolBar: null
            , footer: null

            //回调函数
            , callback: undefined
            , completed: undefined

            //其它
            , border: true//边框
            , checkBox: false//复选
            , onDblClick: true//双击

            //view视图
            , view: null//视图
            , groupField: ''//分组字段
            , fit: true//全屏
            , fitColumns: true//自适应

            , onLoadSuccess: undefined//分组字段
            //, frozenColumns: undefined
            //, columns: undefined
            , defaultValue: null//默认选中
        };
        _default = $.extend(_default, obj);
        $.extend(obj, _default);

        obj.entity = {
            iconCls: 'icon-table'
            , title: obj.title
            , key: obj.key
            , idField: obj.key
            , nowrap: true
            , fit: obj.fit
            , striped: true
            , fitColumns: false
            , rownumbers: false
            , remoteSort: true
            , multiSort: false
            , singleSelect: obj.checkBox == true ? false : true
            , checkOnSelect: true
            , fitColumns: obj.fitColumns
            , selectOnCheck: true
            , method: 'post'
            , border: obj.border
            , collapsible: false
            , pagination: obj.pagination
            , pageSize: obj.pageSize
            , pageList: obj.pageList
            //,frozenColumns: [obj.frozenColumns]
            //,columns: [obj.columns]
            , toolbar: obj.toolBar
            , footer: obj.footer
            , onDblClickRow: function (rowIndex, rowData) {
                if (obj.onDblClick) {
                    obj.rowIndex = rowIndex;
                    obj.rowData = rowData;
                    $.fn.DataGrid.onDblClickRow(obj);
                }
            }
            , onSortColumn: function (sort, order) {
                obj.orderBy.sort = sort;
                obj.orderBy.order = order;
                $('#' + obj.id).datagrid('loading');//等待 
                $.fn.DataGrid.Ajax(obj);//请求ajax                 
            }
            , onLoadSuccess: function () {
                $('#' + obj.id).datagrid('loaded');
            }
            //, onSelect: function (index, row) {
            //    debugger
            //    var a = index;
            //    var b = row;
            //}
            //, onUnselect: function (index, row) {
            //    debugger
            //    var a = index;
            //    var b = row;
            //}
            , onCheck: function (index, row) {
                $.fn.DataGrid.addDefaultValue(obj, [row]);
            }
            , onUncheck: function (index, row) {
                $.fn.DataGrid.removeDefaultValue(obj, [row]);
            }
            , onSelectAll: function (row) {
                $.fn.DataGrid.addDefaultValue(obj, row);
            }
            , onUnselectAll: function (row) {
                $.fn.DataGrid.removeDefaultValue(obj, row);
            }
        };
        //首次初始化
        $.fn.DataGrid.renderPage(obj);//分页
        $('#' + obj.id).datagrid(obj.entity);//表格
        $('#' + obj.id).datagrid('loading');//等待 
        $.fn.DataGrid.Ajax(obj);//请求ajax
    }
    , addDefaultValue: function (obj, rows) {
        if (obj.defaultValue == null) {
            obj.defaultValue = [];
        }
        $.each(rows, function (i, item) {
            var index = $.inArray(item["id"], obj.defaultValue);
            if (index < 0) {
                obj.defaultValue.push(item["id"]);
            }
        })
    }
    , removeDefaultValue: function (obj, rows) {
        if (obj.defaultValue == null) {
            obj.defaultValue = [];
        }
        var rowsID = [];
        $.each(rows, function (i, item) {
            rowsID.push(item["id"]);
        })

        $.each(rowsID, function (i, item) {
            var index = $.inArray(item, obj.defaultValue);
            if (index > -1) {
                obj.defaultValue.splice(index, 1);
            }
        })
    }
    , renderPage: function (obj) {
        $(obj.footer).pagination({
            total: obj.pages.total
            , pageSize: obj.pages.pageSize
            , pageNumber: obj.pages.pageNumber
            , pageList: obj.pages.pageList
            , onSelectPage: function (pageNumber, pageSize) {
                $('#' + obj.id).datagrid('loading');
                obj.pages.pageNumber = pageNumber;
                obj.pages.pageSize = pageSize;
                $.fn.DataGrid.Ajax(obj);
            }
            , onChangePageSize: function (pageSize) {
                $('#' + obj.id).datagrid('loading');
                obj.pages.pageSize = pageSize;
                $.fn.DataGrid.Ajax(obj);
            }
            , onRefresh: function (pageNumber, pageSize) {
                //$('#' + obj.id).datagrid('loading');
                //obj.pages.pageNumber = pageNumber;
                //obj.pages.pageSize = pageSize;
                //$.fn.DataGrid.Ajax(obj);
            }
        });
    }
    , loadData: function (obj) {
        $('#' + obj.id).datagrid('loadData', []);
        $('#' + obj.id).datagrid('loadData', obj.tempData);

        if (obj.defaultValue != null) {
            var rows = $('#' + obj.id).datagrid('getRows');
            $.each(rows, function (i, e) {
                var index = $.inArray(e["id"], obj.defaultValue);
                if (index > -1) {
                    $('#' + obj.id).datagrid('checkRow', i);
                }
            });
        }
    }
    , onRefresh: function (obj) {
        $.fn.DataGrid.SearchToolBar(obj);
        obj.data.Filter = obj.filters;

        $('#' + obj.id).datagrid('loading');
        $.fn.DataGrid.Ajax(obj);//请求ajax 
    }
    , Ajax: function (obj) {
        var page = $.extend({}, obj.pages, obj.orderBy);
        //obj.data["Page"] = page;
        obj.data = page;

        try {
            $.InvokeAjax({
                url: obj.url,
                data: obj.data,
                callBack: function (result) {

                    obj.tempData = result.Data;
                    obj.pages.total = result.total;

                    $.fn.DataGrid.renderPage(obj);
                    $.fn.DataGrid.loadData(obj, result.Data);
                }
            });
        } catch (e) {
            $('#' + obj.id).datagrid('loaded');
        }
    }

    //双击事件
    , onDblClickRow: function (obj) {
        var queryStr = "";
        if (obj.isReadonly != undefined) {
            queryStr = "&isReadonly=" + obj.isReadonly;
        }
        var _url = Url(obj.detailsUrl, "guid=" + obj.rowData[obj.key] + "&dgID=" + obj.id + queryStr);
        $.layerOpen({ title: obj.dialogName, width: obj.dialogWidth, height: obj.dialogHeight, url: _url, callback: obj.callback });
    }
    , View: function (obj) {
        var row = $('#' + obj.id).datagrid('getSelected');
        if (row != null) {
            var _url = Url(obj.detailsUrl, "guid=" + row[obj.key] + "&dgID=" + obj.id);

            $.DialogOpen(obj.dialogName, obj.dialogWidth, obj.dialogHeight, _url, obj.callback);
        } else {
            layer.msg('您还没有选择任何记录!');
        }
    }
    , Insert: function (obj, urlParams) {
        var _url = Url(obj.addUrl, "dgID=" + obj.id);
        if (urlParams != undefined) {
            _url += "&" + urlParams;
        }
        $.layerOpen({ title: obj.dialogName, width: obj.dialogWidth, height: obj.dialogHeight, url: _url, callback: obj.callback });
    }
    , Update: function (obj, urlParams) {
        var row = $('#' + obj.id).datagrid('getSelected');
        if (row != null) {
            var _url = Url(obj.editUrl, "guid=" + row[obj.key] + "&dgID=" + obj.id);
            if (urlParams != undefined) {
                _url += "&" + urlParams;
            }
            $.layerOpen({ title: obj.dialogName, width: obj.dialogWidth, height: obj.dialogHeight, url: _url, callback: obj.callback });
        } else {
            layer.msg('您还没有选择任何记录!');
        }
    }
    , Delete: function (obj) {
        var row = $('#' + obj.id).datagrid('getSelections');
        if (row.length > 0) {
            layer.confirm('您确定要删除选定的 ' + row.length + ' 条记录吗？', { icon: 2, title: '删除操作' }, function (index) {
                var id = obj.key;
                obj.deleteData["id"] = row[0][obj.key];
                $.InvokeAjax({
                    url: obj.deleteUrl,
                    data: obj.deleteData,
                    callBack: function (data) {
                        $.fn.DataGrid.Ajax(obj);//请求ajax 
                    }
                });
                layer.close(index);
            });
        }
        else {
            layer.msg('请选择要删除的数据!');
        }
    }
    , OpenSearch: function (obj) {
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['60%', '60%'], //宽高,
            maxmin: true,
            title: "搜索",
            content: $.fn.DataGrid.getSearchHtml(obj),
            btnAlign: 'c',
            btn: ['搜索', '取消', "清空"],
            yes: function (index, layero) {
                $.fn.DataGrid.Search(obj);
                layer.close(index);
            },
            btn2: function (index, layero) { },
            btn3: function (index, layero) {
                $.fn.DataGrid.SearchClear(obj);
                return false;
            }
        });
    }

    , getSearchHtml: function (obj) {
        var arr = new Array();
        obj.filters.forEach(function (item) {
            if (arr[item.col] != null && arr[item.col] != undefined) {
                arr[item.col].push(item);
            }
            else {
                arr[item.col] = [];
                arr[item.col].push(item);
            }
        });

        var temp = [];
        temp.push('<div class="z_wrap"><ul class="info">');
        for (var key in arr) {
            temp.push("<li>");
            temp.push("<em class='l_name'>" + arr[key][0].title + "：</em>");

            var className = (arr[key].length == 1) ? "r_con1" : "r_con2";
            temp.push("<div class='" + className + "'>");

            arr[key].forEach(function (item) {
                var title = item.title;
                var id = "s_" + item.name;
                var value = "";
                if (item.value != null && item.value != undefined) {
                    value = item.value;
                }
                if (item.type == "datetime") {
                    temp.push("<input id='" + id + "' name='" + id + "' type='text' data-prompt-position='bottomRight' value='" + value + "' onclick='WdatePicker()' readonly/>");
                }
                else {
                    temp.push("<input id='" + id + "' name='" + id + "' type='text' data-prompt-position='bottomRight' value='" + value + "'/>");
                }
            });
            temp.push("</div></li>");
        }
        temp.push("</ul></div>");
        return temp.join("");
    }
    , Search: function (obj) {
        obj.filters.forEach(function (item) {
            item.value = $.GetValue("s_" + item.name);
        });
        $.fn.DataGrid.onRefresh(obj);
    }
    , SearchToolBar: function (obj) {
        var html = [];
        var ls = "";
        if (obj.filters != undefined) {
            obj.filters.forEach(function (item) {
                var temp = [];
                if (item.value != null && item.value != "") {
                    html.push(ls + '<a href="#" onclick="$.fn.DataGrid.SearchToolBarDel(obj,\'' + item.name + '\');">(' + item.title + ' ' + item.filter + ' ' + item.value + ')</a>');
                    ls = "and";
                }
            });
        }
        if (html.length > 0) {
            html.splice(0, 0, "搜索条件:");
        }
        $("#toolbarSearchtext").html(html.join(""));
    }
    , SearchToolBarDel: function (obj, name) {
        $.each(obj.filters, function (index, item) {
            if (item.name == name) {
                item.value = null;
            }
        });
        $.fn.DataGrid.onRefresh(obj);
    }
    , SearchClear: function (obj) {
        $.each(obj.filters, function (index, item) {
            var id = "s_" + item.name;
            $("#" + id).val("");
        });
    }
};

//***************************************************


$.fn.Checkbox = {
    DataBind: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.groupName = $.SetAttValue(obj, "groupName", obj.id);
        obj.value = $.SetAttValue(obj, "Value", "id");
        obj.name = $.SetAttValue(obj, "Name", "Name");
        obj.data = $.SetAttValue(obj, "data", null);


        $("#" + obj.id).html("");
        $.each(obj.data, function (i, value) {
            var html = "<label><input name=\"" + obj.groupName + "\" value=\"" + this[obj.value] + "\" type=\"checkbox\" />" + this[obj.name] + "</label>";
            $("#" + obj.id).append(html);
        });
    }
};

$.fn.Radio = {
    DataBind: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.groupName = $.SetAttValue(obj, "groupName", obj.id);
        obj.value = $.SetAttValue(obj, "Value", "id");
        obj.name = $.SetAttValue(obj, "Name", "Name");
        obj.data = $.SetAttValue(obj, "data", null);


        $("#" + obj.id).html("");
        $.each(obj.data, function (i, value) {
            var html = "<label><input name=\"" + obj.groupName + "\" value=\"" + this[obj.value] + "\" type=\"radio\" />" + this[obj.name] + "</label>";
            $("#" + obj.id).append(html);
        });
    }
};

$.fn.Select = {
    DataBind: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.value = $.SetAttValue(obj, "Value", "id");
        obj.name = $.SetAttValue(obj, "Name", "Name");
        obj.data = $.SetAttValue(obj, "data", null);


        $("#" + obj.id).empty();
        $("#" + obj.id).append("<option value=\"\">全部</option>");
        $.each(obj.data, function (i, value) {
            var html = "";
            if (this.children == null || this.children.length == 0) {
                html = "<option data=\"" + value.Levels + "\" value=\"" + this[obj.value] + "\">" + this[obj.name] + "</option>";
            }
            else {
                html += "<optgroup label='" + this[obj.name] + "'>";
                $.each(this.children, function () {
                    html += "<option value=\"" + this[obj.value] + "\">" + this[obj.name] + "</option>";
                });
                html += "</optgroup>";
            }
            $("#" + obj.id).append(html);

            if (obj.callFunction != undefined) {
                obj.callFunction(obj.data);
            }
        });
    }
};

$.fn.Echarts = {
    Bar: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.data = $.SetAttValue(obj, "data", []);
        obj.dataAxis = $.SetAttValue(obj, "dataAxis", []);
        obj.barWidth = $.SetAttValue(obj, "barWidth", '40%');
        obj.color0 = $.SetAttValue(obj, "color0", '#83bff6');
        obj.color1 = $.SetAttValue(obj, "color1", '#188df0');

        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById(obj.id));

        // 指定图表的配置项和数据  
        option = {
            xAxis: {
                data: obj.dataAxis,
            }, tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid: {
                left: '1%',
                right: '1%',
                bottom: '1px',
                containLabel: true
            },
            yAxis: {
            },
            series: [
                {
                    name: obj.title,
                    type: 'bar',
                    barWidth: obj.barWidth,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(
                            0, 0, 0, 1,
                            [
                                { offset: 0, color: obj.color0 },
                                { offset: 0.5, color: obj.color1 },
                                { offset: 1, color: obj.color1 }
                            ]
                        )
                    },
                    data: obj.data
                }
            ]
        };
        myChart.setOption(option);
    },
    Line: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.data = $.SetAttValue(obj, "data", null);
        obj.showTitle = $.SetAttValue(obj, "showTitle", false);
        obj.data.type = 'line';
        var defaultgrid = {
            x: 80,
            y: 30,
            x2: 30,
            y2: 30,
            width: '90%'
        };
        obj.grid = $.extend(defaultgrid, obj.grid);

        var myChart = echarts.init(document.getElementById(obj.id));
        option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },

            title: {
                text: !obj.showTitle ? obj.data.TitleText : ""
            },

            //color: ['#C23531', '#2F4554', '#61A0A8', '#D48265', '#91C7AE', '#749F83', '#CA8622', '#BDA29A', '#6E7074'],
            legend: {
                data: obj.data.LegendData
            },
            grid: obj.grid,
            xAxis: [
                {
                    type: 'category',
                    data: obj.data.XAxisData
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: obj.data.SeriesData
        };
        myChart.setOption(option);
    },
    Pie: function (obj) {
        obj.id = obj.id;
        obj.data = $.SetAttValue(obj, "data", null);
        var myChart = echarts.init(document.getElementById(obj.id));

        if (obj.click) {
            myChart.on('click', function (param) {
                obj.click({ CategoryID: param.data.CategoryID });
            })
        }
        var option = {
            title: {
                text: obj.data.TitleText == null ? "" : obj.data.TitleText,
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            //color: ['#C23531', '#2F4554', '#61A0A8', '#D48265', '#91C7AE', '#749F83', '#CA8622', '#BDA29A', '#6E7074'],
            legend: {
                orient: 'vertical',
                x: 'left',
                data: obj.data.LegendData
            },
            calculable: true,
            series: [
                {
                    name: '统计',
                    type: 'pie',
                    radius: '55%',
                    center: ['60%', '60%'],
                    data: obj.data.SeriesData
                }
            ]
        }
        myChart.setOption(option);
    },
    PiePie: function (obj) {
        obj.id = obj.id;
        obj.data = $.SetAttValue(obj, "data", null);
        var myChart = echarts.init(document.getElementById(obj.id));

        if (obj.click) {
            myChart.on('click', function (param) {
                obj.click({ CategoryID: param.data.CategoryID });
            })
        }
        var option = {
            title: {
                text: obj.data.TitleText == null ? "" : obj.data.TitleText,
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            color: ['#C23531', '#2F4554', '#61A0A8', '#D48265', '#91C7AE', '#749F83', '#CA8622', '#BDA29A', '#6E7074'],
            legend: {
                orient: 'vertical',
                x: 'left',
                data: obj.data.LegendData
            },
            calculable: true,
            series: [
                {
                    name: '统计',
                    type: 'pie',
                    selectedMode: 'single',
                    radius: [0, '20%'],

                    label: {
                        normal: {
                            position: 'inner'
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data: obj.data.SeriesData
                },
                {
                    name: '统计',
                    type: 'pie',
                    radius: ['46%', '55%'],
                    data: obj.data.SeriesZiData
                }
            ]
        }
        myChart.setOption(option);
    }
};

$.fn.Tree = {
    Init: function (obj) {
        //必须属性
        obj.id = obj.id;
        obj.data = $.SetAttValue(obj, "data", null);
        obj.checkbox = $.SetAttValue(obj, "checkbox", false);
        obj.cascadeCheck = $.SetAttValue(obj, "cascadeCheck", true);
        obj.onlyLeafCheck = $.SetAttValue(obj, "onlyLeafCheck", false);

        obj.onClick = $.SetAttValue(obj, "onClick", null);
        obj.onCheck = $.SetAttValue(obj, "onCheck", null);


        //obj.data = obj.url;

        $("#" + obj.id).tree({
            data: obj.data,
            url: obj.url,
            lines: true,
            animate: true,
            shadow: true,
            checkbox: obj.checkbox,
            cascadeCheck: obj.cascadeCheck,
            onlyLeafCheck: obj.onlyLeafCheck,
            onClick: function (node) {
                var node = $("#tree").tree('getSelected');
                if (obj.onClick != null) {
                    obj.onClick(node);
                }
            },
            onCheck: function (node, checked) {
                if (obj.onCheck != null) {
                    obj.onCheck(node, checked);
                }
            }
        });
    }
};

function Url(url, params) {
    if (url == undefined) {
        url = "";
    }
    if (params == "") { }
    else if (url.indexOf("?") > -1) {
        url += "&" + params;
    }
    else {
        url += "?" + params;
    }
    return url;
}